package com.yc.thread.basic;


/**
 * @author zwei
 * @create 2024-07-15 14:55
 */
public class Test16_deadlock implements Runnable {
    int flag = 1;
    static final Object o1 = new Object();
    static final Object o2 = new Object();

    public static void main(String[] args) {
        Test16_deadlock td1=new Test16_deadlock();  //任务1
        Test16_deadlock td2=new Test16_deadlock();  //任务2
        td1.flag = 1;
        td2.flag = 2;
        Thread t1=new Thread(td1,"线程1");
        Thread t2=new Thread(td2,"线程2");
        t1.start();
        t2.start();
    }

    @Override
    public void run() {
        System.out.println("flag=" + flag);
        if (flag == 1) {
            synchronized (o1) {         //对任务1： 取o1，sleep，不释放o1  再取o2
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o2) {
                    System.out.println("1");
                }
            }
        }
        if (flag==2){
            synchronized (o2){      //对任务2： 取o2，sleep，不释放o2  再取o1
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (o1){
                    System.out.println("2");
                }
            }
        }
    }
}
